package cn.bld.controller;

import cn.bld.entity.StorageRecord;
import cn.bld.entity.SysSupplier;
import cn.bld.entity.SysUser;
import cn.bld.service.SysSupplierService;
import cn.bld.utils.MyFileUtil;
import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("supplier")
public class SysSupplierContorller {
    @Autowired
    private SysSupplierService sysSupplierService;
    @GetMapping("page")
    public  String page(@RequestParam(value = "querySupCode" ,required = false, defaultValue = "") String querySupCode,
                        @RequestParam(value = "querySupName",required = false,defaultValue = "")String querySupName,
                        @RequestParam(value = "pageIndex",required = false,defaultValue = "1")Integer pageIndex, Model model){
        Integer size = 8;
        int totalCount = sysSupplierService.findCount(querySupCode,querySupName);
        int totalPageCount = totalCount%size==0?totalCount/size:totalCount/size+1;
        List<SysSupplier> supplierList = sysSupplierService.findByCondition(querySupCode, querySupName, pageIndex, size);

        model.addAttribute("totalCount",totalCount);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("currentPageNo",pageIndex);
        model.addAttribute("supplierList",supplierList);
        model.addAttribute("querySupCode",querySupCode);
        model.addAttribute("querySupName",querySupName);

        return "supplier/list";
    }
    @GetMapping("/add")
    public String add(){
        return "supplier/add";
    }
    @GetMapping("/supplierExist")
    @ResponseBody
    public String checkSupCode(String supCode){
        int i = 1;
        Map<String,Object> map = new HashMap<>();
        try{
            if (StringUtils.isNullOrEmpty(supCode)){
                map.put("exist",-1);
                map.put("msg","用户名不能为空");
                return JSON.toJSONString(map);
            }
            i = sysSupplierService.checkSupCode(supCode);
            if (i==0){
                map.put("exist",0);
            }else {
                map.put("exist",1);
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("exist",-1);
            map.put("msg","服务器访问异常，请稍后重试");
        }
        return JSON.toJSONString(map);
    }
    @PostMapping("toAdd")
    public String addSupplier(SysSupplier sysSupplier, MultipartFile companyLicPics, MultipartFile orgCodePics, HttpSession session) throws IOException {
        String path =session.getServletContext().getRealPath("upload");
        if(!companyLicPics.isEmpty()){
            String newFilename = MyFileUtil.uploadFile(companyLicPics, path);
            sysSupplier.setCompanyLicPic("upload/"+newFilename);
        }
        if (!orgCodePics.isEmpty()){
            String newFilename = MyFileUtil.uploadFile(orgCodePics, path);
            sysSupplier.setOrgCodePic("upload/"+newFilename);
        }
        SysUser loginUser = (SysUser) session.getAttribute("userSession");
        sysSupplier.setCreatedUserId(loginUser.getId());
        int i = sysSupplierService.insertSupplier(sysSupplier);
        if (i==1){
            return "redirect:/supplier/page";
        }
        return "redirect:/WEB-INF/jsp/supplier/add.jsp";
    }
    @GetMapping("/simpleList")
    @ResponseBody
    public String findRoles(){
        return JSON.toJSONString(sysSupplierService.findall());
    }
    @DeleteMapping("del/{supId}")
    @ResponseBody
    public String del(@PathVariable Integer supId){
        Map<String,Object> map = new HashMap<>();
//        if (sysSupplierService.findGyId(userid)==null){
//            map.put("delResult","notexist");
//            return JSON.toJSONString(map);
//        }
        int i = sysSupplierService.deleteSupplier(supId);
        if (i==1){
            map.put("delResult","true");
        }else {
            map.put("delResult","false");
        }
        return JSON.toJSONString(map);
    }
    @GetMapping("/view/{opr}/{id}")
    public String view(@PathVariable Integer id, Model model, @PathVariable String opr){
        model.addAttribute(("supplier"),sysSupplierService.findById(id));
        if("v".equals(opr)){
            return "/supplier/view";
        }else {
            return "/supplier/update";
        }

    }
    @PostMapping("update")
    public String update(SysSupplier sysSupplier, HttpSession session){
        SysUser loginUser = (SysUser) session.getAttribute("userSession");
        sysSupplier.setUpdatedUserId(loginUser.getId());
        int i = sysSupplierService.updateSupplier(sysSupplier);
        return "redirect:/supplier/page";
    }
}
